package com.samphanie.auiu.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import com.samphanie.auiu.common.ui.component.AuiuBaseFragment
import com.samphanie.auiu.R
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import com.samphanie.auiu.biz.account.AccountManager
import com.samphanie.auiu.common.ui.view.loadCircle
import com.samphanie.auiu.common.ui.view.loadCorner
import com.samphanie.auiu.common.utils.SPUtil
import com.samphanie.auiu.databinding.FragmentProfileBinding
import com.samphanie.auiu.http.ApiFactory
import com.samphanie.auiu.http.api.AccountApi
import com.samphanie.auiu.http.api.ProfileApi
import com.samphanie.auiu.http.api.profileApiService
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse
import com.samphanie.auiu.library.utils.AuiuDisplayUtil
import com.samphanie.auiu.model.CourseNotice
import com.samphanie.auiu.model.Notice
import com.samphanie.auiu.model.UserProfile
import com.samphanie.auiu.route.AuiuRoute
import com.samphanie.auiu.ui.banner.core.AuiuBannerMo

class ProfileFragment : AuiuBaseFragment<FragmentProfileBinding>() {
    private val REQUEST_CODE_LOGIN_PROFILE: Int = 1001

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.profileNotice.setOnClickListener {
            AuiuRoute.startActivity(context, destination = AuiuRoute.Destination.NOTICE_LIST)
        }

        // 设置 底部四个功能item 入口 图标文案
        binding.itemCourse.text = getString(R.string.item_notify)
        binding.itemCollection.text = getString(R.string.item_collection)
        binding.itemAddress.text = getString(R.string.item_address)
        binding.itemHistory.text = getString(R.string.item_history)

        queryBannerData()

        if (AccountManager.isLogin()) {
            queryLoginUserData()
        } else {
            updateDefaultUI()
        }
    }

    private fun queryBannerData() {
        profileApiService().bannerNoticeList().enqueue(object : AuiuCallback<List<Notice>> {
            override fun onSuccess(response: AuiuResponse<List<Notice>>) {
                if (response.code == AuiuResponse.SUCCESS && response.data != null) {
                    updateBanner(response.data)
                }
            }

            override fun onFailed(throwable: Throwable) {
                showToast(throwable.message)
            }

        })
    }

    private fun updateDefaultUI() {
        binding.username.text = getString(R.string.profile_not_login)
        binding.loginDesc.text = getString(R.string.profile_login_desc)
        binding.userAvatar.setImageResource(R.drawable.ic_avatar_default)
        binding.userAvatar.setOnClickListener {
            AuiuRoute.startActivity(
                activity,
                destination = AuiuRoute.Destination.ACCOUNT_LOGIN,
                requestCode = REQUEST_CODE_LOGIN_PROFILE
            )
            AccountManager.login(context) {
                queryLoginUserData()
            }
        }

        binding.tabItemCollection.text = spannableTabItem(0, getString(R.string.profile_tab_item_collection))
        binding.tabItemHistory.text = spannableTabItem(10, getString(R.string.profile_tab_item_history))
        binding.tabItemLearn.text = spannableTabItem(20, getString(R.string.profile_tab_item_learn))
    }

    private fun queryLoginUserData() {
        AccountManager.getUserProfile(this, { profile ->
            if (profile != null) {
                updateUserUI(profile)
            } else {
                showToast(getString(R.string.fetch_user_profile_failed))
            }
        }, onlyCache = false)
    }

    private fun updateUserUI(userProfile: UserProfile) {
        binding.username.text = userProfile.nickname

        binding.loginDesc.text = getString(R.string.profile_login_desc_welcome_back)
        binding.userAvatar.loadCircle(userProfile.avatar)

        binding.tabItemCollection.text = spannableTabItem(userProfile.favoriteCount, getString(R.string.profile_tab_item_collection))
        binding.tabItemHistory.text = spannableTabItem(userProfile.browseCount, getString(R.string.profile_tab_item_history))
        binding.tabItemLearn.text = spannableTabItem(userProfile.learnMinutes, getString(R.string.profile_tab_item_learn))

        queryCourseNotice()
    }

    private fun queryCourseNotice() {
        profileApiService().notice().enqueue(object : AuiuCallback<CourseNotice> {
            override fun onSuccess(response: AuiuResponse<CourseNotice>) {
                if (response.successful() && response.data != null) {
                    binding.notifyCount.text = response.data!!.total.toString()
                    binding.notifyCount.visibility = View.VISIBLE
                }
            }

            override fun onFailed(throwable: Throwable) {
                showToast(throwable.message)
            }

        })
    }

    private fun updateBanner(bannerNoticeList: List<Notice>?) {
        if (bannerNoticeList == null || bannerNoticeList.isEmpty()) return
        val models = mutableListOf<AuiuBannerMo>()
        bannerNoticeList.forEach{
            val auiuBannerMo = object : AuiuBannerMo() {}
            auiuBannerMo.url = it.cover
            models.add(auiuBannerMo)
        }
        binding.auiuBanner.setBannerData(R.layout.layout_profile_banner_item, models)
        binding.auiuBanner.setBindAdapter { viewHolder, mo, position ->
            val imageView = viewHolder.findViewById<ImageView>(R.id.banner_item_image)
            imageView.loadCorner(mo.url, AuiuDisplayUtil.dp2px(10f, resources))
        }
        binding.auiuBanner.setOnBannerClickListener { viewHolder, bannerMo, position ->
//            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(bannerNoticeList[position].url))
//            startActivity(intent)
            AuiuRoute.startActivity4Browser(bannerNoticeList[position].url)
        }

        binding.auiuBanner.visibility = View.VISIBLE
    }

    private fun spannableTabItem(topText: Int, bottomText: String): CharSequence? {
        var spanStr = topText.toString()
        var ssb = SpannableStringBuilder()
        var ssTop = SpannableString(spanStr)

        ssTop.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.color_000)),
            0,
            ssTop.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        ssTop.setSpan(AbsoluteSizeSpan(18, true), 0, ssTop.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        ssTop.setSpan(StyleSpan(Typeface.BOLD), 0, ssTop.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        ssb.append(ssTop)
        ssb.append(bottomText)
        return ssb
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

//        if (requestCode == REQUEST_CODE_LOGIN_PROFILE && resultCode == Activity.RESULT_OK && data != null) {
//            queryLoginUserData()
//        }
    }

    private fun showToast(message: String?) {
        if (message == null) return
        Toast.makeText(
            context,
            message,
            Toast.LENGTH_SHORT
        ).show()
    }

    override fun initialize(savedInstanceState: Bundle?) {
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_profile
    }
}